package repository

import (
	"github.com/honwee/awm/internal/model"
	"github.com/honwee/awm/pkg/database"
	"gorm.io/gorm"
	"time"
)

type WorkflowRunRepository struct {
	db *gorm.DB
}

func NewWorkflowRunRepository() *WorkflowRunRepository {
	return &WorkflowRunRepository{
		db: database.DB,
	}
}

// Create 创建工作流运行记录
func (r *WorkflowRunRepository) Create(run *model.WorkflowRun) error {
	return r.db.Create(run).Error
}

// FindByWorkflowRunID 根据工作流运行ID查询记录
func (r *WorkflowRunRepository) FindByWorkflowRunID(workflowRunID string) (*model.WorkflowRun, error) {
	var run model.WorkflowRun
	err := r.db.Where("workflow_run_id = ?", workflowRunID).First(&run).Error
	if err != nil {
		return nil, err
	}
	return &run, nil
}

// FindByUserID 根据用户ID查询记录
func (r *WorkflowRunRepository) FindByUserID(userID string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	var runs []model.WorkflowRun
	var total int64

	if err := r.db.Model(&model.WorkflowRun{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := r.db.Where("user_id = ?", userID).
		Offset(offset).
		Limit(limit).
		Order("created_at DESC").
		Find(&runs).Error

	return runs, total, err
}

// FindByStatus 根据状态查询记录
func (r *WorkflowRunRepository) FindByStatus(status string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	var runs []model.WorkflowRun
	var total int64

	if err := r.db.Model(&model.WorkflowRun{}).Where("status = ?", status).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := r.db.Where("status = ?", status).
		Offset(offset).
		Limit(limit).
		Order("created_at DESC").
		Find(&runs).Error

	return runs, total, err
}

// UpdateStatus 更新工作流运行状态
func (r *WorkflowRunRepository) UpdateStatus(workflowRunID string, status string) error {
	updates := map[string]interface{}{
		"status": status,
	}

	if status == model.StatusSucceeded || status == model.StatusFailed {
		updates["finished_at"] = time.Now()
	}

	return r.db.Model(&model.WorkflowRun{}).
		Where("workflow_run_id = ?", workflowRunID).
		Updates(updates).Error
}

// UpdateStatusWithFinishedAt 更新工作流运行状态和完成时间
func (r *WorkflowRunRepository) UpdateStatusWithFinishedAt(workflowRunID string, status string, finishedAt *time.Time) error {
	updates := map[string]interface{}{
		"status":      status,
		"finished_at": finishedAt,
	}

	return r.db.Model(&model.WorkflowRun{}).
		Where("workflow_run_id = ?", workflowRunID).
		Updates(updates).Error
}

// FindByWorkflowID 根据工作流ID查询记录
func (r *WorkflowRunRepository) FindByWorkflowID(workflowID string, offset, limit int) ([]model.WorkflowRun, int64, error) {
	var runs []model.WorkflowRun
	var total int64

	if err := r.db.Model(&model.WorkflowRun{}).Where("workflow_id = ?", workflowID).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := r.db.Where("workflow_id = ?", workflowID).
		Offset(offset).
		Limit(limit).
		Order("created_at DESC").
		Find(&runs).Error

	return runs, total, err
}
